﻿using NWNT.Dal;
using NWNT.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Net.Mail;
using System.Net;
using System.IO;
using NWNT.Dal.Database;
using System.Web.Security;
using System.Web.Script.Serialization;
using System.Security.Principal;

namespace NWNT.Web.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private NWNT.Dal.IUnitOfWork uow;

        private CustomPrincipal UserDetails
        {
            get
            {
                return ((CustomPrincipal)System.Web.HttpContext.Current.User);
            }
        }

        private MediaPartialModel GetMedia()
        {
            IQueryable<Media> model = uow.MediaRepository.GetAll();

            MediaPartialModel result = new MediaPartialModel()
            {
                SecondaryMedia1 = from PM in model.Where(m => m.MediaTypeId == 2)
                                  select new SecondaryMediaModel
                                  {
                                      MediaId = PM.MediaId,
                                      Header1 = PM.Header1,
                                      Header2 = PM.Header2
                                  },
                SecondaryMedia2 = from PM in model.Where(m => m.MediaTypeId == 3)
                                  select new SecondaryMediaModel
                                  {
                                      MediaId = PM.MediaId,
                                      Header1 = PM.Header1,
                                      Header2 = PM.Header2
                                  }

            };

            return result;
        }

        public HomeController()
        {
            this.uow = new UnitOfWork();
        }

        [AllowAnonymous]
        public ActionResult Index()
        {
            var data = System.Web.HttpContext.Current.User;
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            ViewBag.LatestMedia = uow.MediaRepository.GetAll().Where(m => m.MediaTypeId == 1).OrderByDescending(m => m.CreatedOn).FirstOrDefault();
            ViewBag.LatestBlog = uow.MediaRepository.GetAll().Where(m => m.MediaTypeId == 3).OrderByDescending(m => m.CreatedOn).FirstOrDefault();
            ViewBag.LatestNewsUpdate = uow.MediaRepository.GetAll().Where(m => m.MediaTypeId == 2).OrderByDescending(m => m.CreatedOn).FirstOrDefault();
            ViewBag.Testimonials = from PM in uow.MediaRepository.GetAll().Where(m => m.MediaTypeId == 4).OrderByDescending(m => m.CreatedOn).Take(2)
                                   select new PrimaryMediaPartialModel
                                   {
                                       MediaId = PM.MediaId,
                                       Header1 = PM.Header1,
                                       Header2 = PM.Header2,
                                       CreatedOn = PM.CreatedOn
                                   };

            return View();
        }

        [AllowAnonymous]
        public ActionResult About()
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            return View();
        }

        [AllowAnonymous]
        public ActionResult Template()
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            return View();
        }

        [HttpGet]
        public ActionResult Questionnaire()
        {
            var questionnaireArea = uow.QuestionAreaRepository.GetAll();
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            //var questionnaireOptions = uow.QuestionnaireOptionRepository.GetAll();
            //var questionnaireAreaOptions = uow.QuestionnaireAreaOptionMappingRepository.GetAll();
            //var questionnaire = uow.QuestionnaireRepository.GetAll();

            List<QuestionnaireAreaModel> model = (from a in questionnaireArea
                                                  select new QuestionnaireAreaModel
                                                  {
                                                      QuestionAreaId = a.QuestionAreaId,
                                                      Area = a.Area//,
                                                      //Questions = (from q in a.Questionnaires
                                                      //             select new QuestionModel
                                                      //             {
                                                      //                 QuestionId = q.Id,
                                                      //                 Question = q.Questions,
                                                      //                 Options = (from o in a.QuestionnaireAreaOptionMappings
                                                      //                            select new QuestionOptionsModel
                                                      //                            {
                                                      //                                Optionid = o.OptionId,
                                                      //                                OptionName = o.QuestionnaireOption.OptionName
                                                      //                            }).AsEnumerable()
                                                      //             }).AsEnumerable(),
                                                      //Options = (from o in a.QuestionnaireAreaOptionMappings
                                                      //           select new QuestionOptionsModel
                                                      //           {
                                                      //               Optionid = o.OptionId,
                                                      //               OptionName = o.QuestionnaireOption.OptionName
                                                      //           }).AsEnumerable()
                                                  }).ToList();//.ToList();

            foreach (var area in model)
            {
                area.Questions = (from q in questionnaireArea.FirstOrDefault(m => m.QuestionAreaId == area.QuestionAreaId).Questionnaires
                                  select new QuestionModel
                                                                      {
                                                                          QuestionId = q.Id,
                                                                          Question = q.Questions//,
                                                                          //Options = (from o in a.QuestionnaireAreaOptionMappings
                                                                          //           select new QuestionOptionsModel
                                                                          //           {
                                                                          //               Optionid = o.OptionId,
                                                                          //               OptionName = o.QuestionnaireOption.OptionName
                                                                          //           }).AsEnumerable()
                                                                      }).ToList();

                area.Options = (from o in questionnaireArea.FirstOrDefault(m => m.QuestionAreaId == area.QuestionAreaId).QuestionnaireAreaOptionMappings
                                select new QuestionOptionsModel
                                {
                                    Optionid = o.OptionId,
                                    OptionName = o.QuestionnaireOption.OptionName
                                }).ToList();
            }
            ViewBag.PreviousVisible = false;
            return View(model);
        }

        [HttpPost]
        public ActionResult Questionnaire(List<QuestionnaireAreaModel> model)
        {
            //Dictionary<string, int> areaWiseScore = new Dictionary<string, int>();
            //int score = 0;
            StressResult dbModel = new StressResult() { UserId = this.UserDetails.UserId, CreatedOn = DateTime.Now, CreatedBy = this.UserDetails.UserId };
            //dbModel.StressResultDetails.a
            foreach (QuestionnaireAreaModel area in model)
            {
                foreach (QuestionModel question in area.Questions)
                {
                    dbModel.StressResultDetails.Add(new StressResultDetail() { QuestionId = question.QuestionId, OptionId = question.SelectedOptionId });
                    //score += uow.QuestionAreaRepository.GetAll().FirstOrDefault(m => m.QuestionAreaId == area.QuestionAreaId).QuestionnaireAreaOptionMappings.FirstOrDefault(m => m.OptionId == question.SelectedOptionId).Score;
                }

                //areaWiseScore.Add(area.Area, score);
                //score = 0;
            }

            uow.StressResultRepository.Insert(dbModel);
            uow.Save();

            //StressResultModel result = new StressResultModel();
            //result.Areas = areaWiseScore.Keys.ToArray();
            //result.Results = areaWiseScore.Values.ToArray();
            //result.FinalScore = result.Results.Sum();
            return RedirectToAction("StressResult", new { stressResultId = dbModel.StressResultId });
        }

        //[HttpGet]
        //public ActionResult StressResult(StressResultModel result)
        //{
        //    return View("StressResult", result);
        //}

        [HttpGet]
        public ActionResult StressResult(int stressResultId)
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            Dictionary<string, int> areaWiseScore = new Dictionary<string, int>();
            int score = 0;
            IEnumerable<QuestionArea> questionArea = uow.QuestionAreaRepository.GetAll().AsEnumerable();
            var selectedQuestionOptions = uow.StressResultDetailRepository.GetAll().Where(m => m.StressResultId == stressResultId);

            foreach (QuestionArea area in questionArea)
            {
                foreach (Questionnaire question in area.Questionnaires)
                {
                    var selectedQuestion = selectedQuestionOptions.Where(m => m.QuestionId == question.Id).FirstOrDefault();
                    if (selectedQuestion != null)
                    {
                        score += uow.QuestionAreaRepository.GetAll()
                            .FirstOrDefault(m => m.QuestionAreaId == area.QuestionAreaId)
                            .QuestionnaireAreaOptionMappings.FirstOrDefault(m => m.OptionId == selectedQuestion.OptionId).Score;
                    }
                }

                areaWiseScore.Add(area.Area, score);
                score = 0;
            }

            StressResultModel result = new StressResultModel();
            result.Areas = areaWiseScore.Keys.ToArray();
            result.Results = areaWiseScore.Values.ToArray();
            result.FinalScore = result.Results.Sum();
            return View("StressResult", result);
        }

        [HttpGet]
        public ActionResult QuestionnaireAreas()
        {
            IEnumerable<QuestionArea> result = uow.QuestionAreaRepository.GetAll().AsEnumerable();
            return View(result);
        }

        [HttpGet]
        public ActionResult QuestionArea(int areaId = 0)
        {
            QuestionAreaModel result = null;
            if (areaId != 0)
            {
                result = (from qa in uow.QuestionAreaRepository.GetAll()
                          where qa.QuestionAreaId == areaId
                          select new QuestionAreaModel
                          {
                              QuestionAreaId = qa.QuestionAreaId,
                              Area = qa.Area,
                              Description = qa.Description,
                              SelectedQuestionOptions = (from qam in qa.QuestionnaireAreaOptionMappings
                                                         orderby qam.Order
                                                         select qam.OptionId),
                              SelectedQuestionOptionsScores = (from qam in qa.QuestionnaireAreaOptionMappings
                                                               orderby qam.Order
                                                               select qam.Score)
                          }).FirstOrDefault();



                result.QuestionOptions = (from qo in uow.QuestionnaireOptionRepository.GetAll()
                                          select new QuestionOptionsModel
                                          {
                                              Optionid = qo.Optionid,
                                              OptionName = qo.OptionName,
                                          }).ToList();
            }
            else
            {
                result = new QuestionAreaModel();

            }
            return View(result);
        }

        //[HttpPost]
        //public ActionResult QuestionArea([Bind(Exclude = "Id")]QuestionAreaModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (model.QuestionAreaId > 0)
        //        {
        //            uow.Context.UpdateQuestionArea(model.QuestionAreaId, model.Area, model.Description, null, null, 17, DateTime.Now);
        //        }
        //        else
        //        {
        //            uow.Context.UpdateQuestionArea(null, model.Area, model.Description, 17, DateTime.Now, 17, DateTime.Now);
        //        }
        //        return RedirectToAction("QuestionAreaList");
        //    }
        //    else
        //    {
        //        ViewBag.Error = ModelState.Values.ElementAt(0).Errors.ElementAt(0);
        //        return View();
        //    }


        //}

        [HttpGet]
        public ActionResult QuestionAreaList()
        {
            IEnumerable<QuestionAreaModel> result = null;
            result = (from qa in uow.QuestionAreaRepository.GetAll()
                      select new QuestionAreaModel
                      {
                          QuestionAreaId = qa.QuestionAreaId,
                          Area = qa.Area,
                          Description = qa.Description,
                          //QuestionOptions = qa.QuestionnaireAreaOptionMappings.Select(m => m.OptionId),
                          Order = qa.Order
                      }).OrderBy(e => e.Order).AsEnumerable();
            return View(result);
        }

        [HttpGet]
        public ActionResult UserProfile(int userId = 0)
        {
            userId = this.UserDetails.UserId;
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            ViewBag.Prefixes = uow.PrefixRepository.GetAll().ToList();
            //ViewBag.States = uow.StateRepository.GetAll().ToList();
            ViewBag.Countries = (from c in uow.CountryRepository.GetAll()
                                 select new
                                 {
                                     CountryId = c.CountryId,
                                     CountryCode = c.CountryCode,
                                     States = (from s in c.States
                                               select new
                                               {
                                                   StateId = s.StateId,
                                                   StateCode = s.StateCode
                                               }
                                              )
                                 }
                                ).ToList();

            UserInfo dbModel = uow.UserInfoRepository.GetAll().FirstOrDefault(m => m.UserId == userId);
            UserInfoModel model = new UserInfoModel();
            model.UserId = dbModel.UserId;
            model.UserName = dbModel.UserName;
            model.RelationshipCode = dbModel.RelationshipCode;
            model.CompanyName = dbModel.CompanyName;
            model.PrefixId = dbModel.PrefixId;
            model.FirstName = dbModel.FirstName;
            model.MiddleName = dbModel.MiddleName;
            model.LastName = dbModel.LastName;
            model.DateOfBirth = dbModel.DateOfBirth;
            model.Gender = dbModel.Gender;
            model.UserTypeId = dbModel.UserTypeId;
            model.ParentId = dbModel.ParentId;

            model.UserProfiles = new List<UserProfileModel>();
            UserProfileModel userProfile;
            int counter = 1;

            foreach (UserProfile dbUserProfile in dbModel.UserProfile)
            {
                userProfile = new UserProfileModel();
                userProfile.Counter = counter;
                userProfile.UserProfileId = dbUserProfile.UserProfileId;
                userProfile.UserId = dbUserProfile.UserId;
                userProfile.Address1 = dbUserProfile.Address1;
                userProfile.Address2 = dbUserProfile.Address2;
                userProfile.City = dbUserProfile.City;
                userProfile.Pincode = dbUserProfile.Pincode;
                userProfile.CountryId = dbUserProfile.CountryId;
                userProfile.StateId = dbUserProfile.StateId;
                userProfile.MobileNo = dbUserProfile.MobileNo;
                userProfile.PhoneNo = dbUserProfile.PhoneNo;
                userProfile.Email = dbUserProfile.Email;
                userProfile.Fax = dbUserProfile.Fax;
                userProfile.Website = dbUserProfile.Website;
                userProfile.ApplicableStressOMeter = dbUserProfile.ApplicableStressOMeter;
                userProfile.CreatedBy = this.UserDetails.UserId;
                userProfile.CreatedOn = DateTime.Now;
                userProfile.EditedBy = this.UserDetails.UserId;
                userProfile.EditedOn = DateTime.Now;

                model.UserProfiles.Add(userProfile);
                counter += 1;
            }
            //model.UserProfiles.Add(new UserProfileModel() { UserProfileId = 1, Counter = 1, Address1 = "29/24 east patel nagar", Address2 = "nd", City = "delhi", Pincode = 110026, StateId = 6, MobileNo = 98989898, PhoneNo = 989, Email = "ripuranjan@gmail.com", Fax = 989, Website = "ripuranjan.com", ApplicableStressOMeter = dbModel.ApplicableStressOMeter });
            //model.UserProfiles.Add(new UserProfileModel() { UserProfileId = 2, Counter = 2, Address1 = "24/29 east patel nagar", Address2 = "nd1", City = "delhi1", Pincode = 110026, StateId = 6, MobileNo = 98989898, PhoneNo = 989, Email = "ranjanripu@gmail.com", Fax = 989, Website = "ranjanripu.com", ApplicableStressOMeter = "S" });

            model.StressResults = uow.StressResultRepository.GetAll().Where(m => m.UserId == userId).Select(m => new StressResultsDateModel() { StressResultId = m.StressResultId, StressDate = m.CreatedOn }).OrderBy(m => m.StressDate).ToList();

            return View("UserProfile", model);
        }

        [HttpPost]
        public JsonResult UserProfile(UserInfoModel model)
        {
            UserInfo dbModel;
            if (model.UserId != 0)
            {
                dbModel = uow.UserInfoRepository.GetAll().FirstOrDefault(m => m.UserId == model.UserId);

                if (dbModel != null)
                {
                    dbModel.RelationshipCode = model.RelationshipCode;
                    dbModel.PrefixId = model.PrefixId;
                    dbModel.FirstName = model.FirstName;
                    dbModel.MiddleName = model.MiddleName;
                    dbModel.LastName = model.LastName;
                    dbModel.DateOfBirth = model.DateOfBirth;
                    dbModel.Gender = model.Gender;
                    dbModel.EditedBy = this.UserDetails.UserId;
                    dbModel.EditedOn = DateTime.Now;

                    if (model.UserProfiles != null)
                    {
                        NWNT.Dal.Database.UserProfile dbUserProfile;

                        foreach (UserProfileModel userProfile in model.UserProfiles)
                        {
                            if (userProfile.UserProfileId != 0)
                            {
                                dbUserProfile = dbModel.UserProfile.FirstOrDefault(m => m.UserProfileId == userProfile.UserProfileId);
                                if (dbUserProfile != null)
                                {
                                    dbUserProfile.Address1 = userProfile.Address1;
                                    dbUserProfile.Address2 = userProfile.Address2;
                                    dbUserProfile.City = userProfile.City;
                                    dbUserProfile.Pincode = userProfile.Pincode;
                                    dbUserProfile.CountryId = userProfile.CountryId;
                                    dbUserProfile.StateId = userProfile.StateId;
                                    dbUserProfile.MobileNo = userProfile.MobileNo;
                                    dbUserProfile.PhoneNo = userProfile.PhoneNo;
                                    dbUserProfile.Email = userProfile.Email;
                                    dbUserProfile.Fax = userProfile.Fax;
                                    dbUserProfile.Website = userProfile.Website;
                                    dbUserProfile.ApplicableStressOMeter = userProfile.ApplicableStressOMeter;
                                    dbUserProfile.EditedBy = this.UserDetails.UserId;
                                    dbUserProfile.EditedOn = DateTime.Now;
                                }
                            }
                            else
                            {
                                dbUserProfile = new UserProfile();
                                dbUserProfile.Address1 = userProfile.Address1;
                                dbUserProfile.Address2 = userProfile.Address2;
                                dbUserProfile.City = userProfile.City;
                                dbUserProfile.Pincode = userProfile.Pincode;
                                dbUserProfile.CountryId = userProfile.CountryId;
                                dbUserProfile.StateId = userProfile.StateId;
                                dbUserProfile.MobileNo = userProfile.MobileNo;
                                dbUserProfile.PhoneNo = userProfile.PhoneNo;
                                dbUserProfile.Email = userProfile.Email;
                                dbUserProfile.Fax = userProfile.Fax;
                                dbUserProfile.Website = userProfile.Website;
                                dbUserProfile.ApplicableStressOMeter = userProfile.ApplicableStressOMeter;
                                dbUserProfile.CreatedBy = this.UserDetails.UserId;
                                dbUserProfile.CreatedOn = DateTime.Now;
                                dbUserProfile.EditedBy = this.UserDetails.UserId;
                                dbUserProfile.EditedOn = DateTime.Now;

                                dbModel.UserProfile.Add(dbUserProfile);
                            }
                        }
                    }

                    uow.UserInfoRepository.Update(dbModel);
                    uow.Save();
                }
            }
            else
            {
                dbModel = new UserInfo();

                dbModel.UserName = model.RelationshipCode;
                dbModel.Password = model.Password;
                dbModel.RelationshipCode = model.RelationshipCode;
                dbModel.PrefixId = model.PrefixId;
                dbModel.FirstName = model.FirstName;
                dbModel.MiddleName = model.MiddleName;
                dbModel.LastName = model.LastName;
                dbModel.DateOfBirth = model.DateOfBirth;
                dbModel.Gender = model.Gender;
                dbModel.CreatedBy = this.UserDetails.UserId;
                dbModel.CreatedOn = DateTime.Now;
                dbModel.EditedBy = this.UserDetails.UserId;
                dbModel.EditedOn = DateTime.Now;

                if (model.UserProfiles != null)
                {
                    NWNT.Dal.Database.UserProfile dbUserProfile;

                    foreach (UserProfileModel userProfile in model.UserProfiles)
                    {
                        dbUserProfile = new UserProfile();
                        dbUserProfile.Address1 = userProfile.Address1;
                        dbUserProfile.Address2 = userProfile.Address2;
                        dbUserProfile.City = userProfile.City;
                        dbUserProfile.Pincode = userProfile.Pincode;
                        dbUserProfile.CountryId = userProfile.CountryId;
                        dbUserProfile.StateId = userProfile.StateId;
                        dbUserProfile.MobileNo = userProfile.MobileNo;
                        dbUserProfile.PhoneNo = userProfile.PhoneNo;
                        dbUserProfile.Email = userProfile.Email;
                        dbUserProfile.Fax = userProfile.Fax;
                        dbUserProfile.Website = userProfile.Website;
                        dbUserProfile.ApplicableStressOMeter = userProfile.ApplicableStressOMeter;
                        dbUserProfile.CreatedBy = this.UserDetails.UserId;
                        dbUserProfile.CreatedOn = DateTime.Now;
                        dbUserProfile.EditedBy = this.UserDetails.UserId;
                        dbUserProfile.EditedOn = DateTime.Now;

                        dbModel.UserProfile.Add(dbUserProfile);
                    }
                }

                uow.UserInfoRepository.Insert(dbModel);
                uow.Save();
            }
            return new JsonResult() { Data = "Success" }; // View("UserProfile", model);
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult Logoff(string UserLogin, string UserPassword)
        {
            this.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));

            this.Response.Cache.SetValidUntilExpires(false);

            this.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            this.Response.Cache.SetNoStore();
            FormsAuthentication.SignOut();

            return this.RedirectToAction("index");
        }

        [AllowAnonymous]
        [HttpPost]
        public JsonResult Login(string UserLogin, string UserPassword)
        {
            //UserInfo UserInfo = new UserInfo();
            //UserInfo.UserName = UserLogin;
            //UserInfo.Password = UserPassword;
            var result= new JsonResult();
            var userData = uow.UserInfoRepository.GetAll().Where(m => m.UserName == UserLogin && m.Password == UserPassword).FirstOrDefault();
            if (userData != null)
            {
                Session["UserName"] = userData.UserName;
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                UserInformation user = new UserInformation() { UserId = userData.UserId, UserName = userData.UserName };
                string userDataString = serializer.Serialize(user);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                                         1,
                                         userData.UserName,
                                         DateTime.Now,
                                         DateTime.Now.Add(FormsAuthentication.Timeout),
                                         false,
                                         userDataString);
                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie formCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(formCookie);
                //return RedirectToActionPermanent("Index", "Home");
                result.Data = new { result = "Success" };
            }

            //return RedirectToActionPermanent("Index", "Home", new { message = "invalidlogin" });
            result.Data = new { result = "Failure", message = "Invalid User Name or Password." };
            return result;
        }

        //
        // GET: /Account/Register
        [AllowAnonymous]
        [HttpGet]
        public ActionResult Register()
        {
            return PartialView();
        }

        //
        // POST: /Account/Register
        [AllowAnonymous]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            bool isSuccess = true;
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipCreateStatus.Success;
                if (uow.UserInfoRepository.GetAll().Where(e => e.UserName == model.UserName).Count() > 0)
                {
                    createStatus = MembershipCreateStatus.DuplicateUserName;
                    isSuccess = false;
                }
                if (isSuccess)
                {
                    uow.UserInfoRepository.Insert(new UserInfo()
                    {
                        UserName = model.UserName,
                        Password = model.Password,

                        UserTypeId = 4,
                        EditedOn = DateTime.Now,
                        CreatedOn = DateTime.Now

                    });
                    uow.Save();
                    var userData = uow.UserInfoRepository.GetAll().Where(m => m.UserName == model.UserName).FirstOrDefault();

                    Session["UserName"] = userData.UserName;
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    UserInformation user = new UserInformation() { UserId = userData.UserId, UserName = userData.UserName };
                    string userDataString = serializer.Serialize(user);
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                                             1,
                                             userData.UserName,
                                             DateTime.Now,
                                             DateTime.Now.Add(FormsAuthentication.Timeout),
                                             false,
                                             userDataString);
                    string encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie formCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    Response.Cookies.Add(formCookie);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
                return PartialView(model);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion






        //[HttpGet]
        //[AllowAnonymous]
        //public ActionResult TinyMice()
        //{
        //    return View();
        //}

        [AllowAnonymous]
        public ActionResult HealingPlanet()
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            ViewBag.Media = GetMedia();
            return View();
        }

        [AllowAnonymous]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [AllowAnonymous]
        public ActionResult Faq()
        {
            ViewBag.Media = GetMedia();
            return View();
        }

        [AllowAnonymous]
        public ActionResult Disclaimer()
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            ViewBag.Media = GetMedia();
            return View();
        }

        [AllowAnonymous]
        public ActionResult TermsCondition()
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            return View();
        }
        [AllowAnonymous]
        [HttpGet]
        public ActionResult StressOMeter()
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            ViewBag.Media = GetMedia();
            return View();
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult Media(int mediaTypeId, int mediaId = 0)
        {
            ViewBag.Quotes = uow.QuoteRepository.GetAll().Where(m => m.IsActive).OrderBy(m => m.Order).Select(m => m.Quote1).ToList();
            IQueryable<Media> model = uow.MediaRepository.GetAll();
            if (mediaId == 0)
            {
                MediaPartialModel result = new MediaPartialModel()
                {
                    MediaType = uow.MediaTypeRepository.GetAll().FirstOrDefault(m => m.MediaTypeId == mediaTypeId).MediaTypeDesc,
                    MediaTypeId = mediaTypeId,
                    MediaId = mediaId,
                    PrimaryMediaPartial = from PM in model.Where(m => m.MediaTypeId == mediaTypeId)
                                          orderby PM.CreatedOn descending
                                          select new PrimaryMediaPartialModel
                                          {
                                              MediaId = PM.MediaId,
                                              Header1 = PM.Header1,
                                              Header2 = PM.Header2,
                                              ShortText = PM.ShortText,
                                              CreatedOn = PM.CreatedOn
                                          },
                    SecondaryMedia1 = from PM in model.Where(m => m.MediaTypeId == 2)
                                      orderby PM.CreatedOn descending
                                      select new SecondaryMediaModel
                                      {
                                          MediaId = PM.MediaId,
                                          Header1 = PM.Header1,
                                          Header2 = PM.Header2
                                      },
                    SecondaryMedia2 = from PM in model.Where(m => m.MediaTypeId == 3)
                                      orderby PM.CreatedOn descending
                                      select new SecondaryMediaModel
                                      {
                                          MediaId = PM.MediaId,
                                          Header1 = PM.Header1,
                                          Header2 = PM.Header2
                                      }

                };

                return View(result);
            }
            else
            {
                MediaPartialModel result = new MediaPartialModel()
                {
                    MediaType = uow.MediaTypeRepository.GetAll().FirstOrDefault(m => m.MediaTypeId == mediaTypeId).MediaTypeDesc,
                    MediaTypeId = mediaTypeId,
                    MediaId = mediaId,
                    PrimaryMediaFull = (from PM in model.Where(m => m.MediaTypeId == mediaTypeId && m.MediaId == mediaId)
                                        orderby PM.CreatedOn descending
                                        select new PrimaryMediaFullModel
                                        {
                                            MediaId = PM.MediaId,
                                            Header1 = PM.Header1,
                                            Header2 = PM.Header2,
                                            ShortText = PM.ShortText,
                                            LongText = PM.LongText,
                                            ImagePath = PM.ImagePath,
                                            VideoPath = PM.VideoPath,
                                            CreatedOn = PM.CreatedOn
                                        }).FirstOrDefault(),
                    SecondaryMedia1 = from PM in model.Where(m => m.MediaTypeId == 2)
                                      orderby PM.CreatedOn descending
                                      select new SecondaryMediaModel
                                      {
                                          MediaId = PM.MediaId,
                                          Header1 = PM.Header1,
                                          Header2 = PM.Header2
                                      },
                    SecondaryMedia2 = from PM in model.Where(m => m.MediaTypeId == 3)
                                      orderby PM.CreatedOn descending
                                      select new SecondaryMediaModel
                                      {
                                          MediaId = PM.MediaId,
                                          Header1 = PM.Header1,
                                          Header2 = PM.Header2
                                      }

                };

                return View(result);
            }
        }
    }



    public class MediaPartialModel
    {
        public string MediaType { get; set; }

        public int MediaTypeId { get; set; }

        public int MediaId { get; set; }

        public IEnumerable<PrimaryMediaPartialModel> PrimaryMediaPartial { get; set; }

        public PrimaryMediaFullModel PrimaryMediaFull { get; set; }

        public IEnumerable<SecondaryMediaModel> SecondaryMedia1 { get; set; }

        public IEnumerable<SecondaryMediaModel> SecondaryMedia2 { get; set; }
    }

    //public class MediaFullModel
    //{
    //    public string MediaType { get; set; }

    //    public PrimaryMediaFullModel PrimaryMedia { get; set; }

    //    public IEnumerable<SecondaryMediaModel> SecondaryMedia1 { get; set; }

    //    public IEnumerable<SecondaryMediaModel> SecondaryMedia2 { get; set; }
    //}

    public class PrimaryMediaPartialModel
    {
        public int MediaId { get; set; }
        public string Header1 { get; set; }
        public string Header2 { get; set; }
        public string ShortText { get; set; }
        public DateTime CreatedOn { get; set; }
    }

    public class PrimaryMediaFullModel
    {
        public int MediaId { get; set; }
        public string Header1 { get; set; }
        public string Header2 { get; set; }
        public string ShortText { get; set; }
        public string LongText { get; set; }
        public string ImagePath { get; set; }
        public string VideoPath { get; set; }
        public DateTime CreatedOn { get; set; }
    }

    public class PrimaryMediaModel
    {
        public int MediaId { get; set; }
        public string Header1 { get; set; }
        public string Header2 { get; set; }
        public string ShortText { get; set; }
    }

    public class SecondaryMediaModel
    {
        public int MediaId { get; set; }
        public string Header1 { get; set; }
        public string Header2 { get; set; }
    }
}
